<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    // 3.Promise.race([p1,p2,p3]);执行多个promise对象 ，获取执行最快的promise的结果。
    // Promise.race的实现
    class MyPromise {
      static race (arr) {
        // arr ---> [p1, p2, p3]
        return new Promise((resolve, reject) => {
          arr.forEach(item => {  // item 是promise对象
            item.then(res => {  // then会被调用三次 ，谁执行的快就先调用谁。直接通过resolve返还给新的promise对象的then结果里
              resolve(res);
            }, err => {
              reject(err);
            })
            // 简写
            // item.then(resolve,reject);
          })
          // resolve(111);
          // reject("error")
        })
      }
    }

    let p1 = new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve(111);
      }, 2000)
    })
    let p2 = new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve(222);
      }, 3000)
    })
    let p3 = new Promise((resolve, reject) => {
      setTimeout(() => {
        // resolve(111);
        reject("err");
      }, 1000)
    })

    MyPromise.race([p1, p2, p3]).then(res => {
      console.log(res);
    }, err => {
      console.log(err);
    })
  </script>
</body>

</html>